<?php
/**
 * M2我的催收
 */

namespace app\admin\model;
use think\Db;

class Collection extends Common
{
    protected $name = 'apply';

    public $status = array('3'=>'回收中','4'=>'已违约','5'=>'已完成');
    /**
     * M2我的催收数据
     * @author   yhq <934797303@qq.com>
     * @DateTime 2017-08-08T14:40:23+0800
     * @param    integer                  $uid      当前管理员id
     * @param    string                   $keywords 关键字
     * @param    integer                  $page     页码
     * @param    integer                  $limit    每页数量
     * @return   array
     */
    public function getDataList($uid, $keywords, $page=1, $limit=15, $valuedate, $os = '',$status = "")
    {
        $map = array();
        if($valuedate)
        {
          $valuedate = substr($valuedate,0,10);
          $valuedate = date('Y-m-d',strtotime("$valuedate +1 day"));
          $map['time'] = ['like', '%'.$valuedate.'%'];
        }
        if ($keywords) {
            $map['phone|order_number|name'] = ['like', '%'.$keywords.'%'];
        }
        if($os)
        {
            $map['os'] = $os;
        }

        //增加延期状态
        $map['status'] = array('in','3,4,5,12');
        if(in_array($status, [3,4,5,12]))
        {
            $map2['status'] = $status;
        }

        if($uid != 1)
        {
            $map['merchandiser2'] = $uid;
        }

        $map['transfer'] = 1;
        $map['mtwotransfer'] = 0;
        $map['huishou_status'] = 0;
        $dataCount = $this->where($map)->where($map2)->count();
        $list = $this
            ->where($map)
            ->where($map2)
            ->order('fourth_claim_date desc,auth_type desc,id desc,auth_type desc')
            ->page($page, $limit)
            ->select();
        $list = modelo2array($list);
        foreach($list as $key=>$value)
        {
            $list[$key]['status'] = $this->setOverdue($value['id'],$value['appoint_time'],$value['status']);  //逾期处理
            $list[$key]['info']   = $this->statusInfo($list[$key]['status']); //状态信息
            $list[$key]['user_admin1'] = $this->getNameById($value['check_aid']);      //初审员
            $list[$key]['user_admin2'] = $this->getNameById($value['check2_aid']);     //复审员
            $list[$key]['user_admin3'] = $this->getNameById($value['treasurer']);      //财务员
            $list[$key]['user_admin4'] = $this->getNameById($value['merchandiser']);   //跟单员M1
            $list[$key]['user_admin5'] = $this->getNameById($value['merchandiser2']);  //催收员M2

            $list[$key]['already_money'] = Documentary::alreadyRepay($value, $list[$key]['status']);//已还总金额
            $list[$key]['repay'] = $this->getRepay($list[$key]['status'], $value, $list[$key]['already_money']);//应还总金额
            $list[$key]['surplus'] = $this->getSurplus( $list[$key]['repay'],$list[$key]['status'] );//剩余应还金额

//            $delayMoney = model('v2/Apply')->delayMoney($value);
//            $list[$key]['this_delay_money'] = $delayMoney['money_order'];  //本次延期总费
            $list[$key]['this_delay_money'] = $this->getDelayMoney($value);
            $list[$key]['overdue_day'] = $this->getOverdueDay($value); //逾期天数

            $mapseq['apply_id'] = $value['id'];
            $mapseq['auth_admin'] = 4;
            $dataseq = Db::name('claim_seq')->field('seq')->where($mapseq)->find();
            if(!$dataseq)
            {
              $list[$key]['seq'] = '';
            }else{
                $list[$key]['seq'] = $dataseq['seq'];
              }
        }
        $data['list'] = $list;
        $data['dataCount'] = $dataCount;
        return $data;
    }








    public function getOverruleList($uid, $keywords, $page=1, $limit=15, $valuedate, $os = '',$status = "")
    {
        if ($valuedate != '') {
            $startdate = substr($valuedate, 0, 10);
            $startdate = date('Y-m-d', strtotime("$valuedate +1 day"));

            $enddate = substr($enddate, 0, 10);
            $enddate = date('Y-m-d', strtotime("$enddate +1 day"));

            // $map['appoint_time'] = ['>',$startdate];
            // $map['appoint_time'] = ['<',$enddate];
            $map['c.create_time'] = array('between',array($startdate,$enddate));
        }
        if($keywords){
            $map['a.phone|a.order_number|a.name'] = trim($keywords);
        }
        if($os){
            $map['a.os'] = $os;
        }

        if ($uid != 1) {
            $map['a.merchandiser2'] = $uid;
        }
        if($status != 13 && $status != 0){
            $map['a.status'] = $status;
        }
        $map['a.huishou_status'] = 3;
        $map['a.mtwotransfer'] = 0;
        $map['a.transfer'] = 1;
        if($uid != 1){
            $map['merchandiser2'] = $uid;
        }
        $data = $this->alias('a')
            ->join('consignment c','a.order_number=c.apply_id')
            ->join('admin_user u','a.huishou_aid=u.id')
            ->field('a.id,a.uid,c.create_time time,a.name,a.phone,u.username huishou_aid,a.huishou_status,a.delay_transfer_date,a.fk_time,a.appoint_time,a.order_number,a.money,a.status')
            ->where($map)
            ->order('c.create_time desc')
            ->select();

        $dataCount = $this->alias('a')
            ->join('consignment c','a.order_number=c.apply_id')
            ->join('admin_user u','a.huishou_aid=u.id')
            ->field('count(*)')
            ->where($map)
            ->select();
        $data = modelo2array($data);
        $room = array();

        foreach ($data as $key => $value){

            $days = $this->getOverdueDay($value);                                           //逾期天数
            $data[$key]['overdue_days'] = $days;
            $data[$key]['overdue_money'] = $days*0.11*$value['money'];                      //逾期金额

            //去重 保留最新的发货订单
            if(!isset($room[$value['order_number']])){
                $room[$value['order_number']] = $key;
            }elseif (isset($room[$value['order_number']]) && strtotime($value['time']) > strtotime($data[$room[$value['order_number']]]['time'])){
                unset($data[$room[$value['order_number']]]);
                $room[$value['order_number']] = $key;

            }else{
                unset($data[$key]);
            }

        }
        foreach ($data as $key => $value){
            $data[$key]['status'] = $this->status[$value['status']];
        }
        $list['list'] = $data;
        $list['dataCount'] = $dataCount[0]['count(*)'];
        return $list;



    }




    /**
     * 确认保存备注
     * @author   湛慧平 <1013619199@qq.com>
     * @DateTime 2017-08-10
     * @param                
     */
    public function saveinfo($param)
    {
       $admin_uid = $GLOBALS['userInfo']['id'];
       $apply_id = $param['id'];
       $is_friend    = $param['is_friend'];
       $is_loans     = $param['is_loans'];
       $discount     = $param['discount'];
       $uid          = $param['uid']; 
       $create_time = date('Y-m-d H:i:s',time());
       $data = [
                 'admin_id' => $admin_uid,'uid'=>$uid,
                 'remarks'=>$discount,'is_friends'=>$is_friend,
                 'is_loans'=>$is_loans,'create_time'=>$create_time,
                 'apply_id'=>$apply_id
               ];
       $map['apply_id'] = $apply_id;
       $info = Db::name('apply_bz') ->field('apply_id')->where($map)->find();

       if($info)
       {
          $data = Db::name('apply_bz')->where($map)->update($data);
          if(!$data)
          {
             $this->error = "存取失败";
             return false;
          }
          return true;
       }

          $data = Db::name('apply_bz')->insert($data);
          if(!$data)
          {
             $this->error = "存取失败";
             return false;
          }
          return true;
    }


    //M1保存催收日志
    public function remindernote($param)
    {
      $admin_uid       = $GLOBALS['userInfo']['id'];
      $uid             = $param['uid'];
      $id              = $param['id'];
      $contact_name    = $param['contact_name'];
      $reminder_status = $param['reminder_status'];
      $appoint_time    = $param['appoint_time'];
      $appointtime     = strtotime($appoint_time);
      $status          = $param['status'];
      $contact_type    = $param['contact_type'];
      if(time()>$appointtime&&$status==4)
      {
       $time = (time()-$appointtime)/(60*60*24);
       $days_overdue = intval($time)+1;
      }else
      {
        $days_overdue = 0;
      }

      $reminder_time   =date('Y-m-d H:i:s',time());

      $data = [
                'admin_uid'            =>$admin_uid,
                'uid'                  =>$uid,
                'apply_id'             =>$id,
                'contact_name'         =>$contact_name,
                'reminder_status'      =>$reminder_status,
                'days_overdue'         =>$days_overdue,
                'reminder_time'        =>$reminder_time,
                'reminder_character'   =>'M2',
                'contact_type'         =>$contact_type,
              ];

      $info = Db::name('reminder_note')->insert($data);
      if(!$info)
      {
        $this->error = "失败";
        return false;
      }
        return true;
    }


    /**
     * 用户确认还款
     * @author   湛慧平 <1013619199@qq.com>
     * @DateTime 2017-08-10
     * @param                
     */
    public function repayment($param)
    {
        $uid = $param['uid'];
        $admin_uid = $GLOBALS['userInfo']['id'];
        $id = $param['id'];
        $map['id'] = $id;
        $time = date('Y-m-d H:i:s',time());
        $data = ['status'=>5,'hk_time'=>$time];



        //M2后台确认还款插入订单
        $res = $this->where('id',$id)->find();
        $dataO['apply_id']    = $res['order_number'];
        $dataO['no_order']    = 'M2HT';
        $dataO['acct_name']   = $res['name'];
        $dataO['id_no']       = $res['id_card'];
        $dataO['create_time'] = date('Y-m-d H:i:s');
        $dataO['pay_time']    = date('Y-m-d H:i:s');
        $dataO['pay_type']    = 'XX';
        $dataO['money_order'] = $param['actual_money'];
        $dataO['info_order']  = '后台M2还款';
        $dataO['result_pay']  = 'SUCCESS';
        $dataO['delay_aid']   = $admin_uid;
        $dataO['period']      = $res['period'];
        $info = Db::name('user_order')->insert($dataO);

        $admin_data = ['uid'=>$uid,'admin_user_id'=>$admin_uid,'apply_id'=>$id,'status'=>3,'date'=>$time,'authstatus'=>5];
        $info = $this->save($data,$map);
        $info = Db::name('admin_user_clien')->insert($admin_data);
        if(!$info)
        {
           $this->error = "失败";
           return false;
        }
        return true;
    }

    //统计
    public function search($param)
    {
       $admin_uid = $GLOBALS['userInfo']['id'];
       $value1 = $param['params']['value1'];
       $time1 = substr($value1,0,10);
       $time1 = date('Y-m-d',strtotime("$time1 +1 day"));
       $value2 = $param['params']['value2'];
       $time2 = substr($value2,0,10);
       $time2 = date('Y-m-d',strtotime("$time2 +1 day"));
       $this->startTrans();
       try{

         //总数
         $allinfo = Db::name('admin_user_clien')
                 ->where('date','>',$time1)
                 ->where('date','<',$time2)
                 ->where('admin_user_id','=',$admin_uid)
                 ->where('authstatus','=',5)
                 ->count();

          //回款数
          $info = Db::name('admin_user_clien')
                 ->where('date','>',$time1)
                 ->where('date','<',$time2)
                 ->where('admin_user_id','=',$admin_uid)
                 ->where('status','=',3)
                 ->where('authstatus','=',4)
                 ->count();
       
       if(!$allinfo)
        {
          $data['info']          = 0;
          $data['rate']          = 0;
          $data['allinfo']       = 0;
          return $data;
        }
         
          $data['info']          = $info;                       //回款数 
          $data['allinfo']       = $allinfo;                    //总量
          $data['rate']          = ($info/$allinfo)*100;     
          $data['rate']          = substr($data['rate'], 0,5);  //催款率
          // 提交事务
        $this->commit(); 
        return $data;  
      } catch (\Exception $e) {
          // 回滚事务
        $this->rollback();
        $this->error = '统计失败';
        return false;
      }

    }




    public function mtwoyijioa($params)
    {

        $admin_uid = $GLOBALS['userInfo']['id'];
        $uid = $params['uid'];
        $id = $params['id'];
        $map['id'] = $id;
        $date = date("Y-m-d H:i:s", time());
        $data = ['mtwotransfer_info' => '手动移交', 'mtwotransfer' => 1, 'mtwotransfer_date' => $date];
        $admin_data = ['uid' => $uid, 'authstatus' => 5, 'admin_user_id' => $admin_uid, 'status' => 2, 'apply_id' => $id, 'date' => $date];
        $admin_info = Db::name('admin_user_clien')->insert($admin_data);
        if (!$admin_info) {
            $this->error = "没有保存";
            return false;
        }
        $info = $this->save($data, $map);
        if (!$info) {
            $this->error = "移交失败";
            return false;
        }

        return true;

    }

    /**
     * 功能:    M1留案/取消留案
     * @Author   Mrzhp
     * @email    18702529695@163.com
     * @DateTime 2018-03-26
     * @param    [type]              $params [description]
     * @return   [type]                      [description]
     */
    public function mtwoliuan($params)
    {

        $admin_user_id = $GLOBALS['userInfo']['id'];
        $id        =  $params['id'];
        $map['id'] =  $id;
        if($params['type'] == 1)
        {

            $data = [
                'mtwoliuan' => 1,
                'mtwoliuan_date' => date('Y-m-d H:i:s',time())
            ];

        }
        if($params['type'] == 0)
        {

            $data = [
                'mtwoliuan' => 0
            ];
        }

        $res = $this->save($data,$map);
        if(!$res)
        {
            $this->error = '操作失败';
            return false;
        }

        return true;

    }


}